import React, { Component } from 'react'
import './index.css'
import axios from 'axios'
import {Link} from 'react-router-dom';
export default class Hero extends Component {

    state = {
        types: ['全部','射手','法师','坦克','战士','刺客','辅助'],
        heros: [],
        currentType: ''
    }

    forward = () => {
        // this.props.history.go(1);
        this.props.history.goForward();
    }

    render() {
        return (
            <div className="hero-container">
                {/* 英雄筛选部分 */}
                <div className="filter">
                    <div className="col-xs-6">
                        <button onClick={this.forward} className="btn btn-default btn-sm">前进</button>

                        {this.state.types.map((item, index) => {
                            return <span key={index}><button onClick={this.changeType(item)} key={index} className={`btn btn-default btn-sm ${this.state.currentType === item ? 'btn-primary' : ''}`}>{item}</button>&nbsp;</span>
                        })}
                    </div>

                    <div className="search col-xs-3 pull-right">
                        <div className="input-group">
                        <input type="text" className="form-control" placeholder="关键字" />
                        <span className="input-group-btn">
                            <button className="btn btn-default" type="button">Go!</button>
                        </span>
                        </div>
                    </div>
                </div>
                <div style={{clear:'both'}}></div>
                <hr />

                {/* 英雄列表部分 */}
                <div className="hero-list">
                    {this.state.heros.map(item => {
                        return <div className="item" key={item.id}>
                            <img onClick={this.jump(item.id)} width="100%" src={"http://127.0.0.1:8090" + item.image} alt="" />
                            {item.name}
                        </div>
                    })}
                </div>
            </div>
        )
    }

    jump = (id) => {
        return () => {
            this.props.history.push('/hero-detail/'+ id);
            // this.props.history.replace('/hero-detail/'+id);
        }
    }

    changeType = (type) => {
        
        return async () => {
            //发送请求  http://127.0.0.1:8090/heros?type=法师
            let params = null;
            if(type === '全部'){
                params = {}
            }else{
                params = {type}
            }
            let result = await axios('http://127.0.0.1:8090/heros', {params: params});
            this.setState({
                heros: result.data,
                currentType: type
            })
        }
        
    }

    //http://127.0.0.1:8090/heros
    async componentDidMount(){
        //发送AJAX请求
        let result = await axios('http://127.0.0.1:8090/heros')
        //设置
        this.setState({
            heros: result.data
        })
        
    }
}
